<?php

namespace App\Livewire;

use App\Models\Book;
use App\Models\Category;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;


class CategoryList extends Component
{
    use WithPagination;
    public Category $category;
    public bool $reachedEnd = false;

    public string $keyword = '';
    public string $sort = '';
    public string $status = '';
    public function mount(Category $category)
    {

    }

    public function render()
    {

        return view('livewire.category-list',[
            'books' => $this->getPageData(),
        ])->layoutData([
            'category' => $this->category,
        ]);
    }

    public function search()
    {
        $this->resetPage();
    }

    public function getPageData(): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $query =  Book::query()->where('category_id',$this->category->id);
        if($this->keyword !== ''){
            $query->where('title','like','%'.$this->keyword.'%');
        }
        if($this->status !== ''){
            $query->where('status',$this->status);

        }
        if($this->sort !== ''){
            $query->orderByDesc($this->sort);
        }
        return $query->paginate(16);
    }
}
